package xyj.sparrow.scheduler.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import xyj.sparrow.scheduler.common.Result;
import xyj.sparrow.scheduler.common.Token;
import xyj.sparrow.scheduler.entity.Account;
import xyj.sparrow.scheduler.service.IAccountService;
import xyj.sparrow.scheduler.util.JwtUtil;
import xyj.sparrow.scheduler.vo.AccountVO;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jim
 * @since 2021-06-05
 */
@RestController
@RequestMapping("/api/v1/account")
@Slf4j
@CrossOrigin
public class AccountController {
    @Resource
    private IAccountService iAccountService;

    @PostMapping("/login")
    public Result<Object> login(@RequestBody Account account) {
        Account get = iAccountService.getById(account.getAccountId());
        //校验密码
        String password = SecureUtil.md5(account.getAccountPassword() + account.getAccountSalt());
        if (get == null) {
            return Result.error("账号错误");
        }
        if (!password.equals(get.getAccountPassword())) {
            return Result.error("密码错误");
        }
        get.setAccountPassword(null);
        Token token = new Token(get);
        try {
            String jwt = JwtUtil.createJWT(null, JSONUtil.toJsonStr(token), 2 * 60 * 60 * 1000L);
            return Result.success(new AccountVO(token, jwt));
        } catch (IOException e) {
            log.error("", e);
            return Result.error("签名出错");
        }

    }
}

